package com.vishudha.timer;

import java.text.MessageFormat;

import com.vishudha.timer.domain.VishudhaTime;
import com.vishudha.timer.domain.VishudhaTimeType;

public abstract class VishudhaHelper {
	public static final String defaultMessage = "Remaning Time : {0} Years, {1} Months, {2} Days, {3} Hours, {4} Minutes, {5} Seconds and {6} Tenth of Seconds";
	public static final String defaultAlertMessage = "Mid Alert for the task at " + defaultMessage;
	public static final String defaultFinishMessage = "Timer Event is finished";
	
	public static String getMessage(String message, VishudhaTime time) {
		String formatedMessage = formateMessage(message); 
		return MessageFormat.format(formatedMessage, time.getYears(), time.getMonths(), 
				time.getDays(), time.getHours(), time.getMinutes(), time.getSeconds(), 
				time.getTenthOfASecond());
	}
	
	public static String getMessage(String message, long time) {
		VishudhaTime vishudhaTime = new VishudhaTime(0, 0, 0, 0, 0, 0, 0, time);
		return getMessage(message, vishudhaTime);
	}

	public static String formateMessage(String message) {
		if(message == null || message.isEmpty()) 
			return defaultMessage;
					
		StringBuilder builder = new StringBuilder(message);
		for (VishudhaTimeType timeType : VishudhaTimeType.values()) {
			int timeTypeIndex =  builder.indexOf(timeType.getFormater());
			if(timeTypeIndex > 0) {
				builder.replace(timeTypeIndex, timeTypeIndex + 2, timeType.getFormaterParamId());
			}
		}
		return builder.toString();
	}

	public static long convertToTime(long value, VishudhaTimeType timeType, VishudhaTimeType convertTimeType) {
		return (long) Math.floor(value / (convertTimeType.getDivisionFactor() / timeType.getDivisionFactor()));
	}

	public static long remaningTime(long value, long convertedValue, VishudhaTimeType timeType, VishudhaTimeType convertTimeType) {
		return  value - (convertedValue * (convertTimeType.getDivisionFactor() / timeType.getDivisionFactor()));
	}

	public static long timeInTenthOfASecond (VishudhaTime time) {
		long interval = 0;
		interval += time.getYears() *  VishudhaTimeType.YEAR.getDivisionFactor();
		interval += time.getMonths() *  VishudhaTimeType.MONTH.getDivisionFactor();
		interval += time.getDays() *  VishudhaTimeType.DAYS.getDivisionFactor();
		interval += time.getHours() *  VishudhaTimeType.HOURS.getDivisionFactor();
		interval += time.getMinutes() *  VishudhaTimeType.MINUTES.getDivisionFactor();
		interval += time.getSeconds() *  VishudhaTimeType.SECONDS.getDivisionFactor();
		interval += time.getTenthOfASecond() *  VishudhaTimeType.TENTH_OF_A_SECONDS.getDivisionFactor();
		return interval;  
	}

	public static long reduceTimeIntervel (long time, VishudhaTimeType timeType) {
		return time - timeType.getDivisionFactor();
	}
}
